﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Drawing.Design;
using System.Reflection;
using System.ComponentModel.Design.Serialization;
using EnvDTE;
using EnvDTE80;

namespace ControlsLib
{
    [DesignerCategory("code")]
    [Designer(typeof(DataFormControlDesigner))]
    public partial class DataFormControl2<T> : UserControl where T : class, new()
    {
        private object m_currentObject = null;
        private string m_assemblyPath = string.Empty;
        internal BindingSource m_bindingSource = null;

        public T GetDataFormType 
        {
            get 
            {


                return new T(); 
            } 
        }

        public string AssemblyPath
        {
            get { return m_assemblyPath; }
            internal set 
            { 
                m_assemblyPath = value;
 
                // aggiunge al progetto la reference all'assembly contenente il tipo scelto nel DataFormControl...
                bool ret = SetReference(m_assemblyPath);
            }
        }

        /// <summary>
        /// Add a reference to the .dll containing the selected type...
        /// </summary>
        /// <param name="reference"></param>
        /// <returns></returns>
        public bool SetReference(string reference)
        {
            bool retValue = false;

            try
            {
                Project currentProject = null;
                DTE dte = this.GetService(typeof(EnvDTE.DTE)) as EnvDTE.DTE;
                if (dte == null)
                    return false;

                if (dte.ActiveDocument != null && dte.ActiveDocument.ActiveWindow != null && dte.ActiveDocument.ActiveWindow.Project != null)
                {
                    currentProject = dte.ActiveDocument.ActiveWindow.Project;

                    VSLangProj.VSProject vsProject = (VSLangProj.VSProject)currentProject.Object;

                    vsProject.References.Add(reference);
                    vsProject.Project.Save();
                }

                retValue = true;
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }

            return retValue;
        }

        public object CurrentObject
        {
            get 
            {
                m_bindingSource.EndEdit();
                return m_currentObject; 
            }
            set 
            {
                m_currentObject = value;
                //m_bindingSource.DataSource = m_currentObject.GetType();
            }
        }

        //
        public DataFormControl2()
        { 
            InitializeComponent();

            m_bindingSource = new BindingSource();
        }
    }
}
